<?php

namespace App\Api\V1\Controllers;

use App\Models\Goods;
use App\Models\Order;
use App\Models\Points;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Exceptions\JWTException;

class GoodsController extends Controller
{
    protected $guard = 'api';

    /**
     * 全部商品列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function goods()
    {
        $row = Goods::where('goods_stock', '>', 0)
            ->where('examine_status', 2)
            ->where('is_up', 1)
            ->select(['id','goods_name','goods_price', 'goods_img','goods_stock','is_recommend','goods_number','created_at'])
            ->orderBy('goods_sort')
            ->paginate(10)
            ->toArray();

        $data = [];
        if ($row) {
            $data['current_page'] = $row['current_page'];
            $data['total_page'] = $row['last_page'];
            $data['data'] = $row['data'];
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 可兑换商品
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function canExchangeGoods(Request $request)
    {
        $this->validate($request,[
            'user_id' => 'required'
        ]);

        $user_points = Points::where('user_id', $request->user_id)->first();
        if ($user_points) {
            $row = Goods::where('goods_stock', '>', 0)
                ->where('examine_status', 2)
                ->where('is_up', 1)
                ->where('goods_price', '<=', $user_points->points)
                ->select(['id','goods_name','goods_price', 'goods_img','goods_stock','is_recommend','goods_number','created_at'])
                ->orderBy('goods_sort')
                ->paginate(10)
                ->toArray();

            $data = [];
            if ($row) {
                $data['current_page'] = $row['current_page'];
                $data['total_page'] = $row['last_page'];
                $data['data'] = $row['data'];
            }

            return response()->json([
                'status_code' => 1,
                'message'     => 'success',
                'data'        => $data
            ]);


        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '用戶信息错误',
            ]);
        }

    }

    /**
     * 商品详情
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodsDetails(Request $request)
    {
        $this->validate($request,[
            'user_id' => 'required',
            'goods_id' => 'required'
        ]);

        $user_points = Points::where('user_id', $request->user_id)->first();

        $data = Goods::find($request->goods_id);
        $data['is_canExchange'] = 0;

        if ($data) {
            if ($data->goods_price <= $user_points->points) {
                $data['is_canExchange'] = 1;
            }
        }
        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 兑换商品
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function exchangeGoods(Request $request)
    {
        $this->validate($request,[
            'user_id'  => 'required',
            'goods_id' => 'required',
            'count'    => 'required',
            'step'     => 'required',
        ]);

        $data = Goods::where('id', $request->goods_id)
            ->select(['id','goods_name','goods_price', 'goods_img','goods_stock','is_recommend','goods_number','created_at'])
            ->first();
        $data['is_canExchange'] = 0;

        if ($data) {

            $user_points = Points::where('user_id', $request->user_id)->first();

            $data['points'] = $user_points->points;
            $data['total_amount'] = $data->goods_price * $request->count;
            if ($data['total_amount'] <= $data['points']) {
                $data['is_canExchange'] = 1;
            }

            if ($request->step == 1) {
                $status_code = 1;
                $message = 'success';
            } else {

                if ($data['goods_stock'] < $request->count)
                    return response()->json([
                        'status_code' => 0,
                        'message'     => '兑换失败,库存不足',
                        'data'        => []
                    ]);

                $setting = Points\Setting::first();

                if (!$setting->points_status)
                    return response()->json([
                        'status_code' => 0,
                        'message'     => '兑换功能未开启,暂不能兑换',
                        'data'        => []
                    ]);


                if ($data['is_canExchange'] == 1) {
                    DB::beginTransaction();

                    $order = new Order();
                    $order->order_number = unique();
                    $order->user_id      = $request->user_id;
                    $order->order_amount = $data['total_amount'];
                    $order->pay_time     = date('Y-m-d H:i:s', time());
                    $order->order_status = 2;

                    $flag1 = $order->save();

                    $order_goods = new Order\Goods();
                    $order_goods->order_id     = $order->id;
                    $order_goods->goods_id     = $data->id;
                    $order_goods->goods_name   = $data->goods_name;
                    $order_goods->goods_price  = $data->goods_price;
                    $order_goods->goods_img    = $data->goods_img;
                    $order_goods->goods_num    = $request->count;
                    $order_goods->goods_amount = $data['total_amount'];

                    $flag2 = $order_goods->save();

                    $user_points->points -= $data['total_amount'];
                    $flag3 = $user_points->update();

                    $flag4 = $data->decrement('goods_stock', $request->count);

                    if ($flag1 && $flag2 && $flag3 && $flag4) {
                        DB::commit();
                        $status_code = 1;
                        $message = '兑换成功';
                    } else {
                        DB::rollBack();
                        $status_code = 0;
                        $message = '兑换失败';
                    }
                    $data = [];

                } else {
                    $status_code = 0;
                    $message = '积分不够';
                    $data = [];
                }
            }

        } else {
            $status_code = 0;
            $message = '商品不存在';
            $data = [];
        }
        return response()->json([
            'status_code' => $status_code,
            'message'     => $message,
            'data'        => $data
        ]);
    }

    /**
     * 获取兑换记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function exchangedGoods(Request $request)
    {
        $this->validate($request,[
            'user_id'  => 'required',
        ]);

        $row = Order::where('user_id', $request->user_id)
            ->with('goods')
            ->orderBy('love_orders.created_at', 'desc')
            ->paginate(10)->toArray();

        $data = [];
        if ($row) {
            $data['current_page'] = $row['current_page'];
            $data['total_page'] = $row['last_page'];
            $data['data'] = $row['data'];
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    public function getSetting()
    {
        $setting = Points\Setting::first();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $setting
        ]);
    }

}
